package com.qingyun.web.controller.wxapi;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyV3Result;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderV3Request;
import com.github.binarywang.wxpay.bean.result.enums.TradeTypeEnum;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.qingyun.common.annotation.RateLimiter;
import com.qingyun.common.annotation.RepeatSubmit;
import com.qingyun.common.config.QingYunConfig;
import com.qingyun.common.core.domain.AjaxResult;
import com.qingyun.common.core.page.TableDataInfo;
import com.qingyun.common.enums.LimitType;
import com.qingyun.common.utils.PageUtils;
import com.qingyun.common.utils.ServletUtils;
import com.qingyun.common.utils.ip.IpUtils;
import com.qingyun.security.utils.SecurityUtils;
import com.qingyun.shop.domain.TiktokGoods;
import com.qingyun.shop.domain.TiktokOrder;
import com.qingyun.shop.domain.TiktokOrderItem;
import com.qingyun.shop.domain.TiktokOrderSettlement;
import com.qingyun.shop.domain.bo.order.TiktokOrderQueryBo;
import com.qingyun.shop.domain.vo.OrderVo;
import com.qingyun.shop.domain.vo.TiktokOrderListVo;
import com.qingyun.shop.mapper.TiktokOrderMapper;
import com.qingyun.shop.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Classname ShopOrderController
 * @Author dyh
 * @Date 2021/9/18 17:39
 */
@Api(tags = "商家套餐购买api")
@RestController
@RequestMapping("/miniapp/order")
@AllArgsConstructor
public class ShopOrderController {

	private WxPayService wxPayService;

	private ITiktokOrderService orderService;

	private final TiktokOrderMapper orderMapper;

	private ITiktokOrderItemService orderItemService;

	private ITiktokGoodsService tiktokGoodsService;

	private PayService payService;

	private QingYunConfig qingYunConfig;

	@ApiOperation("订单列表")
	@GetMapping("/list")
	public TableDataInfo<TiktokOrderListVo> listOrders(TiktokOrderQueryBo queryBo) {
		TableDataInfo<TiktokOrderListVo> tiktokOrderListVoTableDataInfo = orderService.queryPageList(queryBo);
		return tiktokOrderListVoTableDataInfo;
	}

	@ApiOperation("通过商品生成订单")
	@RepeatSubmit(intervalTime = 1000)
	@GetMapping("/create")
	public AjaxResult createOrder(Long goodsId,Long count){
		TiktokGoods goods = tiktokGoodsService.getById(goodsId);
		if (ObjectUtil.isNull(goods)||count<0) {
			return AjaxResult.error("参数错误");
		}
		OrderVo order = payService.createOrder(goods, count);
		return AjaxResult.success(order);
	}

	@ApiOperation("通过订单号提交订单获取签名并且支付")
	@RepeatSubmit(intervalTime = 1000)
	@GetMapping("/pay")
	private AjaxResult pay(String orderNum) throws WxPayException {
		TiktokOrder order = orderService.getOne(Wrappers.lambdaQuery(TiktokOrder.class)
			.eq(TiktokOrder::getOrderNum, orderNum)
			.eq(TiktokOrder::getStatus, 0));
		if (ObjectUtil.isNotNull(order)) {
			List<TiktokOrderItem> orderItems = orderItemService.list(Wrappers.lambdaQuery(TiktokOrderItem.class).eq(TiktokOrderItem::getOrderNum, order.getOrderNum()));
			StringBuilder builder = new StringBuilder();
			orderItems.forEach((item)-> builder.append(item.getGoodsName()).append(","));
			String prodName = builder.substring(0, builder.lastIndexOf(","));
			WxPayUnifiedOrderV3Request orderRequest = new WxPayUnifiedOrderV3Request();
			orderRequest.setDescription(prodName);
			orderRequest.setOutTradeNo(orderNum);
			BigDecimal mul = NumberUtil.mul(order.getAmount(), 100);
			WxPayUnifiedOrderV3Request.Amount amount = new WxPayUnifiedOrderV3Request.Amount();
			amount.setCurrency("CNY");
			amount.setTotal(mul.intValue());
			orderRequest.setAmount(amount);
			WxPayUnifiedOrderV3Request.SceneInfo sceneInfo = new WxPayUnifiedOrderV3Request.SceneInfo();
			sceneInfo.setPayerClientIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
			orderRequest.setSceneInfo(sceneInfo);
			orderRequest.setNotifyUrl(qingYunConfig.getProjectUrl() + "/miniapp/order/notice/payOrder");
			WxPayUnifiedOrderV3Request.Payer payer = new WxPayUnifiedOrderV3Request.Payer();
			payer.setOpenid(SecurityUtils.getAppLoginUser().getOpenId());
			orderRequest.setPayer(payer);
			Object orderV3 = wxPayService.createOrderV3(TradeTypeEnum.JSAPI, orderRequest);
			return AjaxResult.success(orderV3);
		}

		return AjaxResult.error("支付失败");
	}

	@ApiOperation("微信支付回调")
	@PostMapping("/notice/payOrder")
	public Map<String,String> notice(@RequestBody String data) throws WxPayException {
		Map<String, String> restMap = new HashMap<>();
		WxPayOrderNotifyV3Result wxPayOrderNotifyV3Result = wxPayService.parseOrderNotifyV3Result(data, null);
		if (wxPayOrderNotifyV3Result.getRawData().getEventType().equals("TRANSACTION.SUCCESS")) {
			WxPayOrderNotifyV3Result.DecryptNotifyResult result = wxPayOrderNotifyV3Result.getResult();
			if (result.getTradeState().equals("SUCCESS")) {
				//订单号
				String outTradeNo = result.getOutTradeNo();
				String transactionId = result.getTransactionId();
				payService.endOrder(outTradeNo,transactionId);
			}
		}
	    restMap.put("code","SUCCESS");
		restMap.put("message","接收成功");
		return restMap;
	}

}
